﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DoubleH.Plugins;
using Table = FCNS.Data.Table;
using System.Data;
using System.ComponentModel;
using DoubleH.Utility;
using System.Windows.Controls.Primitives;
using System.Diagnostics;
using System.IO;
using DoubleH.Utility.Configuration;
using DoubleH.Utility.IO;
using FCNS.Data;
using System.Windows.Threading;
using System.Net;
using FSLib.IPMessager;

namespace DoubleH
{
    /// <summary>
    /// WorkArea.xaml 的交互逻辑
    /// </summary>
    public partial class WorkArea : Window
    {
        public WorkArea()
        {
            InitializeComponent();
        }

        MessageForm messageForm =  new MessageForm(); 
        double scrollVerticalOffset = 0;
        Table.SysConfig sysConfig = null;
        public MenuItemBinding selectedMenu = null;

        PluginManager pluginManager = new PluginManager();
        public PluginManager PluginManager { get { return pluginManager; } }
        /// <summary>
        /// 主机面右上角菜单
        /// </summary>
        public Menu ITopMenu { get { return TopMenu; } }
        /// <summary>
        /// 主界面右下角菜单
        /// </summary>
        public Menu IBottomMenu { get { return bottomMenu; } }

        public void Init()
        {
            if (!DoubleH.Utility.Login.LoginUtility.ShowLoginWindowSuccess(Table.UserS.EnumFlag.操作员))
            {
                System.Environment.Exit(0);
                return;
            }

            InitSysVar();
            //InitUserVar();
            if (FCNS.Data.DbDefine.JieZhuan == null)
                MessageWindow.Show("系统未开账");
            else
                InitMenu();

            InitToolBar();
            InitTreeView();
            InitPagePanel();

            InitAlertMessage();
            InitCpuEvent();
            InitCheckDateIsChangedEvent();
            InitRefreshDataEvent();
            LoadUserUIparams();
            InitNet();
            this.Dispatcher.BeginInvoke(new Action(InitPlugin));
            LoadMessage();
        }

        private void LoadMessage()
        {
            TopMenuClick(Table.SysConfig.EnumModel.消息中心);

            MenuItemBinding tb = treeViewLeftMenu.Items[0] as MenuItemBinding;
            selectedMenu = tb.SubItems[0];
                TreeViewNodeClick();
        }

        private void InitNet()
        {
            DoubleH.Utility.Net.NetUtility.StartNet();
            DoubleH.Utility.Net.NetUtility.LanClient.OnlineHost.HostOnline += (ss, ee) => OnlineHost(ee);
            DoubleH.Utility.Net.NetUtility.LanClient.OnlineHost.HostOffline += (ss, ee) => OfflineHost(ee);
            DoubleH.Utility.Net.NetUtility.LanClient.Commander.TextMessageReceived += (ss, ee) => TextMessageReceived(ee);
        }
       
        private void InitSysVar()
        {
            sysConfig = Table.SysConfig.SysConfigParams;
            Table.StoreS.GetDefault();
            this.Title = FCNS.Data.DbDefine.SystemName;
            this.Closed += (s, ee) => ThisClose();
            this.SizeChanged += (ss, ee) => MessageFormLocation();
            this.Loaded += (ss, ee) => InitMessageForm();
            this.LocationChanged += (ss, ee) => MessageFormLocation();
        }

        //private void InitUserVar()
        //{
        //    if (!loginUser.Content.ToString().Contains(Table.UserS.LoginUser._LoginName))
        //    {
        //        uCPagePanel1.LoadData(null, null);//如果不这样，切换用户就会显示旧用户的资料
        //        treeViewLeftMenu.ItemsSource = null;
        //    }

        //    this.loginUser.Content = "【当前登录用户:" + Table.UserS.LoginUser._LoginName + "】";
        //}

        private void InitPlugin()
        {
            DefaultPluginHost pluginDefaultHost = new DefaultPluginHost();
            pluginDefaultHost.Initialize(this);
            pluginManager.Initialize(pluginDefaultHost);
            pluginManager.LoadAllExtension();
        }

        private void InitAlertMessage()
        {
            System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
            t.Interval = DoubleHConfig.UserConfig.AlertTime * 60000;
            //t.Tick += (ss, ee) => GetMessageS();
            t.Start();
        }

        private void InitTreeView()
        {
            treeViewLeftMenu.MouseUp += (ss, ee) =>
            {
                if (treeViewLeftMenu.SelectedItems.Count == 0)
                    return;

                MenuItemBinding tb = treeViewLeftMenu.SelectedItems[0] as MenuItemBinding;
                if (tb == null)
                    return;
                if (tb == selectedMenu)
                    return;

                //if (tb.SubItems.Count != 0)//选中父类
                //    selectedMenu = tb.SubItems[0];
                //else
                    selectedMenu = tb;
                    TreeViewNodeClick();
            };
        }

        private void InitPagePanel()
        {
            #region 右键菜单
            //MenuItem obj1 = new MenuItem() { Header = "添加到POS禁售列表" };
            //uCPagePanel1.AddMenuItem(obj1);
            //obj1.Click += (ss, ee) =>
            //{
            //    if (uCPagePanel1.SelectedItem == null)
            //        return;

            //    PosStopSale wss = new PosStopSale();
            //    wss.Init(PosStopSale.EnumFlag.Pos禁售商品, null, uCPagePanel1.SelectedItem as Table.ProductS);
            //    wss.ShowDialog();
            //};

            //MenuItem obj2 = new MenuItem() { Header = "编辑收银员列表" };
            //uCPagePanel1.AddMenuItem(obj2);
            //obj2.Click += (ss, ee) =>
            //{
            //    if (uCPagePanel1.SelectedItem == null)
            //        return;

            //    PosStopSale wss = new PosStopSale();
            //    wss.Init(PosStopSale.EnumFlag.Pos操作员, uCPagePanel1.SelectedItem as Table.PosS, null);
            //    wss.ShowDialog();
            //};

            //uCPagePanel1.ContextMenu.Opened += (ss, ee) =>
            //{
            //    obj1.Visibility = (selectedMenu.TableText == DataTableText.可销售商品 ? Visibility.Visible : Visibility.Collapsed);
            //    obj2.Visibility = (selectedMenu.TableText == DataTableText.Pos机器号 ? Visibility.Visible : Visibility.Collapsed);
            //};
            #endregion

            uCPagePanel1.ModeChanged += (ss, ee) => PagePanelModeChanged(ee);
            uCPagePanel1.ItemDoubleClick += (ss) => PagePanelItemDoubleClick();
            uCPagePanel1.HyperlinkClick += (ee) => PagePanelItemClick(ee);
            uCPagePanel1.ScrollMove += new Utility.UC.UCPagePanel.dScrollMove(uCPagePanel1_ScrollMove);
        }

        private void uCPagePanel1_ScrollMove(object sender, ExecutedRoutedEventArgs e)
        {
            if (Table.SysConfig.SysConfigParams.GroupDataCount==0)
                return;

            RoutedCommand command = (RoutedCommand)e.Command;
            if (command.Name == "LineDown")// || command.Name == "ScrollToVerticalOffset"
            {
                System.Windows.Automation.Peers.ScrollViewerAutomationPeer svap;
                ScrollViewer scroll;
                if (e.Source is ListView)
                {
                    System.Windows.Automation.Peers.ListBoxAutomationPeer lvap = new System.Windows.Automation.Peers.ListViewAutomationPeer((ListView)e.Source);
                    svap = lvap.GetPattern(System.Windows.Automation.Peers.PatternInterface.Scroll) as System.Windows.Automation.Peers.ScrollViewerAutomationPeer;
                }
                else
                {
                    System.Windows.Automation.Peers.DataGridAutomationPeer lvap = new System.Windows.Automation.Peers.DataGridAutomationPeer((DataGrid)e.Source);
                    svap = lvap.GetPattern(System.Windows.Automation.Peers.PatternInterface.Scroll) as System.Windows.Automation.Peers.ScrollViewerAutomationPeer;
                }
                scroll = svap.Owner as ScrollViewer;

                //通过偏移量来标识是否已经到底部
                //MessageBox.Show(scroll.VerticalOffset.ToString() + "  " + (scrollVerticalOffset + Table.SysConfig.SysConfigParams.GroupDataCount).ToString());
                if (scroll.VerticalOffset != scrollVerticalOffset)
                    scrollVerticalOffset = scroll.VerticalOffset;
                else
                {
                    if (scroll.VerticalOffset < 1)
                        return;
                    //MessageBox.Show(scroll.VerticalOffset.ToString() + "  " + scroll.VerticalOffset.ToString() + "  " + sqlIndex.ToString());
                    Table.SysConfig.SysConfigParams._Temp_uint+= Table.SysConfig.SysConfigParams.GroupDataCount;
                    BeginBindData();
                }
            }
        }

        private void InitToolBar()
        {
            toolBarTop.Loaded += (ss, ee) => InitToolBarTopUI();
            buttonNew.Click += (ss, ee) => NewObj(); 
            buttonSearch.Click += (ss, ee) => SearchObjByWindow();
            textBoxSearch.TextChanged += (ss, ee) => SearchObjByText();
            buttonHelp.Click+= (ss, ee) => OpenHelp();
            button_import.Click += (ss, ee) => EventImport();
            button_Export.Click += (ss, ee) => EventExport();
            button_zuofei.Click += (ss, ee) => EventZuoFei();
            button_print.Click += (ss, ee) => Print();
            button_printList.Click += (ss, ee) => PrintList();
            button_refresh.Click += (ss, ee) => BeginBindData();
            button_edit.Click += (ss, ee) => EditObj();


            expanderConfig.Header = Table.UserS.LoginUser._GroupSName;
            expanderConfig.Expanded += (ss, ee) => ExpanderConfigOpen();
            expanderConfig.MouseLeave += (ss, ee) => ExpanderConfigClose();
            buttonAppConfig.Click += (ss, ee) => OpenSysconfig();
            buttonLogoff.Click += (ss, ee) => LoginOff();
            buttonPrintConfig.Click += (ss, ee) => PrintConfig();
            buttonCalc.Click += (ss, ee) => OpenCalc();
        }

        /// <summary>
        /// 窗体加载后自动转到‘我的消息’界面和设置一些用户自己的配置
        /// </summary>
        private void LoadUserUIparams()
        {
            UserUIparams dgcb = DoubleHConfig.UserConfig.DataGridBinding.Find(f => f.TableText == DataTableText.待办事项);
            if (dgcb != null)
            {
                DataGridColumnHeaderBinding header = dgcb.Items.Find(f => f.BindingName.Contains("Flag"));
                if (header != null)
                {
                    header.BindingName = DoubleHConfig.UserConfig.ScheduleSUseImageForFlag ? "_Flag" : "Flag";
                    header.ColumnType = DoubleHConfig.UserConfig.ScheduleSUseImageForFlag ? "image" : "";
                }
            }
        }

        //private void HyperlinkClick(object sender, RoutedEventArgs e)
        //{
        //    Hyperlink obj = e.OriginalSource as Hyperlink;
        //    MessageBox.Show((obj == null).ToString());
        //    if (obj == null)
        //        return;

        //    Table.WuLiuS ws = uCPagePanel1.SelectedItem as Table.WuLiuS;
        //    MessageBox.Show((ws == null).ToString());
        //    if (ws == null)
        //        return;

        //    MessageBox.Show(ws._Http);
        //    Process.Start(ws._Http);
        //}

        private void InitCpuEvent()
        {
            Table.CPU.InsertTableObject += new Table.CPU.TableObject(CPU_InsertTableObject);
            Table.CPU.ShenHeTableObject += new Table.CPU.TableObject(CPU_ShenHeTableObject);
            //Table.CPU.DeleteTableObject += new Table.CPU.TableObject(CPU_DeleteTableObject);
            Table.CPU.ReloadTableList += new Table.CPU.TableObject(CPU_ReloadTableList);
        }

        ///// <summary>
        ///// 如果窗体关闭，记得要执行这个清理。因为数据库还没有关闭啊，那么CPU里面的事件就会重复罗。
        ///// </summary>
        //public void Clear()
        //{
        //    Table.CPU.ShenHeStoreSOrderS -= new Table.CPU.StoreOrderSShenHe(WuLiu);
        //}
        DispatcherTimer timer;
        private void InitRefreshDataEvent()
        {
            if (DoubleHConfig.AppConfig.ReloadDataTime <= 60)
                return;

            timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, DoubleHConfig.AppConfig.ReloadDataTime);
            timer.Tick += (ss, ee) => BeginBindData();
            timer.Start();
        }
    }
}